<template>
  <a-card :bordered='false'>

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <a-form layout='inline' style='margin-bottom: 15px'>
        <a-row :gutter='24'>
          <a-col :span='24'>
            <a-form-model-item prop='createTime'>
              <a-radio-group :value='queryParam.year' @change='handleYearChange'>
                <a-radio-button v-for='item in yearList' :key='item' :value='item'>{{ item }}</a-radio-button>
              </a-radio-group>

              <a-range-picker
                style='margin-left: 8px'
                :show-time="{ format: 'HH:mm' }"
                format='YYYY-MM-DD HH:mm'
                :placeholder="['开始时间', '结束时间']"
                @change='onChange'
              />
            </a-form-model-item>

            <a-form-model-item prop='createTime'>
              <a-button @click='searchQuery' type='primary' icon='search'>查询</a-button>
              <a-button @click='searchReset' icon='reload' style='margin-left: 8px'>重置</a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form>

      <div style='margin-bottom: 15px'>
        <a-button v-has='"news:add"' @click='handleAdd' type='primary' icon='plus'>新增</a-button>
        <a-dropdown v-if='selectedRowKeys.length > 0'>
          <a-menu slot='overlay'>
            <a-menu-item key='1' @click='batchDel'>
              <a-icon type='delete' />
              删除
            </a-menu-item>
          </a-menu>
          <a-button style='margin-left: 8px'> 批量操作
            <a-icon type='down' />
          </a-button>
        </a-dropdown>
      </div>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-list style='border-top: 1px solid #e2e2e2' item-layout='vertical' size='large' :pagination='mypagination' :data-source='dataSource'>
        <a-list-item slot='renderItem' :key='item.id' slot-scope='item, index'>
          <img
            class='image'
            slot='extra'
            width='180'
            height='120'
            alt='logo'
            :src='item.mainImage'
          />
          <a-list-item-meta :description='item.description'>
            <a class='list-title' slot='title' @click='showDetail(item)'>{{ item.mainTitle }}</a>
          </a-list-item-meta>
          <div class='content' v-html='getText(item.content).substring(0,250) + "..."'></div>
          <div class='list-footer'>
            <span class='company'>{{ item.viceTitle }}</span>
            <span class='dateTime footer-item'>{{ item.createTime }}</span>
            <a v-has='"news:edit"' class='footer-item' @click='edit(item)'>编辑</a>
            <a v-has='"news:edit"' class='footer-item' style='color: red' @click='del(item)'>删除</a>
          </div>
        </a-list-item>
      </a-list>
    </div>

    <mip-common-news-modal ref='modalForm' @ok='modalFormOk'></mip-common-news-modal>
    <mip-common-news-detail
      ref='newsDetail'
      :visible='detailVisiable'
      @close='close' />
  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import MipCommonNewsModal from './MipCommonNewsModal'
import { ajaxGetDictItems, getDictItemsFromCache } from '@/api/api'
import JInput from '@/components/jeecg/JInput'
import MipCommonNewsDetail from './MipCommonNewsDetail'
import { deleteAction, getAction } from '@api/manage'
import { filterObj } from '@/utils/util'

export default {
  name: 'MipCommonNewsList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    MipCommonNewsModal,
    JInput,
    MipCommonNewsDetail
  },
  data() {
    return {
      description: 'mip_common_news管理页面',
      // 查询条件
      queryParam: {},
      // 查询排序条件
      isorter: {
        column: 'sortNum',
        order: 'DESC'
      },
      /* 分页参数 */
      mypagination:{
        current: 1,
        pageSize: 10,
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        onChange: (page) => {
          this.mypagination.current = page;
          this.loadData()
        },
        showQuickJumper: true,
        total: 0
      },
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '主标题',
          align: 'center',
          dataIndex: 'mainTitle'
        },
        {
          title: '副标题',
          align: 'center',
          dataIndex: 'viceTitle'
        },
        // {
        //   title: '内容',
        //   align: 'center',
        //   dataIndex: 'content'
        // },
        {
          title: '新闻类型',
          align: 'center',
          dataIndex: 'newsType_dictText'
        },
        {
          title: '显示状态',
          align: 'center',
          dataIndex: 'showStatus_dictText'
        },
        {
          title: '新闻属性',
          align: 'center',
          dataIndex: 'newsProperties_dictText'
        },
        {
          title: '访问量',
          align: 'center',
          dataIndex: 'visitNum'
        },
        {
          title: '排序值',
          align: 'center',
          dataIndex: 'sortNum'
        },
        // {
        //   title: '备注',
        //   align: 'center',
        //   dataIndex: 'remarks'
        // },
        // {
        //   title: '状态',
        //   align: 'center',
        //   dataIndex: 'delFlag'
        // },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/mipCommonNews/list',
        delete: '/mipCommonNews/delete',
        deleteBatch: '/mipCommonNews/deleteBatch',
        exportXlsUrl: '/mipCommonNews/exportXls',
        importExcelUrl: '/mipCommonNews/importExcel'

      },
      dictOptions: {},
      superFieldList: [],
      yearList: [],
      year: '',
      dateTimeRange: [],
      detailVisiable: false
    }
  },
  created() {
    this.setYearList()
  },
  methods: {
    loadData(arg) {
      if(!this.url.list){
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.mypagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource = res.result.records||res.result;
          if(res.result.total)
          {
            this.mypagination.total = res.result.total;
          }else{
            this.mypagination.total = 0;
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        }
        if(res.code===510){
          this.$message.warning(res.message)
        }
        this.loading = false;
      })
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if(this.superQueryParams){
        sqp['superQueryParams']=encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter ,this.filters);
      param.field = this.getQueryField();
      param.pageNo = this.mypagination.current;
      param.pageSize = this.mypagination.pageSize;
      return filterObj(param);
    },
    reCalculatePage(count){
      //总数量-count
      let total=this.mypagination.total-count;
      //获取删除后的分页数
      let currentIndex=Math.ceil(total/this.mypagination.pageSize);
      //删除后的分页数<所在当前页
      if(currentIndex<this.mypagination.current){
        this.mypagination.current=currentIndex;
      }
    },
    setYearList() {
      let date = new Date()
      for (let i = 0; i < 3; i++) {
        this.yearList.push(date.getFullYear() - i + '')
      }
      this.queryParam.year = date.getFullYear() + ''
      this.queryParam.dateTimeList = []
    },
    handleYearChange(e) {
      this.queryParam.year = e.target.value
      this.searchQuery()
    },
    onChange(value, dateString) {
      this.queryParam.startTime = dateString[0]
      this.queryParam.endTime = dateString[1]
    },
    initDictData() {
      // 优先从缓存中读取字典配置
      let cacheOption = getDictItemsFromCache(this.dictCode)
      if (cacheOption && cacheOption.length > 0) {
        this.dictOptions = cacheOption
        return
      }
      // 根据字典Code, 初始化字典数组
      ajaxGetDictItems(this.dictCode, null).then((res) => {
        if (res.success) {
          this.dictOptions = res.result
        }
      })
    },
    edit(data) {
      this.$refs.modalForm.title = '编辑';
      this.$refs.modalForm.edit(data);
    },
    showDetail(data) {
      this.detailVisiable = true
      this.$refs.newsDetail.show(data)
    },
    close() {
      this.detailVisiable = false
    },
    getText(str) {
      return str
        .replace(/<[^<>]+>/g, "")
        .replace(/&nbsp;/gi, "");
    },
    del(data) {
      let that = this;
      this.$confirm({
        title: "确认删除",
        content: "是否删除选中数据?",
        onOk: function () {
          deleteAction(that.url.delete, {id: data.id}).then((res) => {
            if (res.success) {
              //重新计算分页问题
              that.reCalculatePage(that.selectedRowKeys.length)
              that.$message.success(res.message);
              that.loadData();
              that.onClearSelected();
            } else {
              that.$message.warning(res.message);
            }
          });
        }
      });
    }
  }
}
</script>
<style scoped>

.list-title {
  font-family: 'Microsoft JhengHei','微软雅黑','Microsoft YaHei',sans-serif;
  font-weight: bolder;
  font-size: 1.2em;
}

.image {
  border-radius: 8px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-right: 30px;
}

.content {
  width: calc(90vw - 350px);
  margin-top: -12px;
  font-family: 'Microsoft JhengHei','微软雅黑','Microsoft YaHei',sans-serif;
  font-size: 1em;
}

.list-footer {
  margin: 12px 0 0;

}

.footer-item {
  margin-left: 10px;
}

.company {
  font-family: 'Microsoft JhengHei','微软雅黑','Microsoft YaHei',sans-serif;
  font-weight: bold;
  font-size: 1em;
}

.dateTime {
  font-family: "Microsoft JhengHei",'微软雅黑',"Microsoft YaHei",sans-serif;
  font-size: 0.9em;
  color: #999999;
}

</style>
